<template>
  <view class="inner">
    <van-notice-bar
      left-icon="volume-o"
      text="尽量完整地回忆出症状和持续时间有助于系统帮您诊断病情"
    />
    <uni-popup type="dialog" ref="popup">
      <uni-popup-dialog
        type="warn"
        title="请打开设置允许使用麦克风!"
        mode="base"
        @confirm="openSetting"
        @close="back"
      >
      </uni-popup-dialog>
    </uni-popup>
    <!-- 唤起麦克风使用功能模块 -->
    <van-cell :title="dep" />
    <!-- <uni-card isFull="true" isShadow="true">{{ dep }}</uni-card> -->
    <!-- 科室 -->

    <!-- 消息栏 -->

    <uni-steps
      :options="problems"
      :active="problemActive"
      class="steps"
      active-color="#ff6781"
    ></uni-steps>
    <!-- 进度条 可以考虑换个颜色 -->
    <swiper
      class="swiper"
      easing-function="default"
      @change="swiperChange"
      :current="problemActive"
      :style="{height:swiperHeight}"
    >
   
      <swiper-item
        v-for="(problem, index) in problems"
        :key="index"
        class="swiper-item"
      > <scroll-view :scroll-y="true" class="scrol">
        <view class="problem-content" v-if="index !== problems.length - 1">
          <view>
            <!-- 问题展示栏 -->
            <uni-card :style="{ display: 'flex', flexDirection: 'row'}">
              <text>{{ problems[index].content }}</text>
            </uni-card>
          </view>
          <!-- 答案栏 -->
          <view class="answer">
            <multi-choice
              :options="[{ content: '有' }, { content: '无' }]"
              @choose="choose"
              v-if="problems[index].type === 'multi-choice'"
            ></multi-choice>

          <!--答案选项卡模块 选择+填空 -->
            <answer
              v-if="
                problems[index].type === 'answer' 
                // problems[index].type === 'answer-more'
              "
              @input="input(index, $event)"
              :defaultAnswers="problem.defaultAnswers"
            ></answer>

          <!-- 判断题模块 -->
            <view v-if="problems[index].type === 'yes-no-answer'">
              <!-- <multi-choice
                :options="[{ content: '有' }, { content: '无' }]"
                @choose="change($event, index)"
              >
              </multi-choice> -->
              <yes-no-answer @choose="change(index,$event)"></yes-no-answer>
             </view>

          <!-- 选择题模块 -->
          <choice v-if="problems[index].type === 'choice'"
            :Answers="problems[index].defaultAnswers"
           @choose="change(index,$event)"></choice>
          </view>
        </view>
        <view v-else>
          <!-- <view class="out-grid">
            <view
              v-for="(problem, index2) in choiceArray"
              :key="index2"
              class="answer-grid"
              @click="problemActive = problem.index"
            >
              <view
                class="single"
                :style="{
                  backgroundColor:
                    answers[problem.index].length !== 0 ? '#3399CC' : 'gray',
                  color:
                    answers[problem.index].length !== 0 ? 'white' : 'black',
                }"
                >{{ alphaBet[answers[problem.index]] || "" }}</view
              >
            </view>
          </view> -->
          <uni-card
           
            v-for="(problem, index2) in problemsContent"
            :key="index2"
            class="answer-bar"
            @click="problemActive = problem.index"
            :title="problem.content"
            >{{ answers[problem.index] || "请回答问题" }}
          </uni-card>
        </view> 
           </scroll-view>
      </swiper-item>

      
    </swiper>
    <!-- 按钮稍微换一下 -->

    <!-- <button @click="swipeToPrevios()" :disabled="problemActive == 0" type="primary"
        style="background-color: #3399cc">上一题</button>
      <button @click="end ? submit() : swipeToNext()" type="primary" style="background-color: #3399cc">{{
        end ? "提交" :
          "下一题"
      }}</button> -->

    <van-goods-action
    placeholder="TRUE">
      <van-goods-action-icon icon="peer-pay" text="页尾" @click="jumpToEnd" />
      <van-goods-action-button
        color="#ff6781"
        text="前一项"
        type="warning"
        :disabled="problemActive == 0"
        @click="swipeToPrevious()"
      />
      <van-goods-action-button
        plain
        color="#ff6781"
        :text="end ? '提交' : '后一项'"
        @click="end ? submit() : swipeToNext()"
      />
    </van-goods-action>
    <!-- 悬浮窗跳转到最后 可以有 但是要改 -->
  </view>
</template>



<script>
import { tts } from "../../utils";
import question from "../../api/question"
export default {
  name: "questionaire",
  mounted() {
    //TODO:

    // tts
    const info = tts.generateAuthoriztion();
    this.taskTTS = uni.connectSocket({
      url: encodeURI(
        `wss://${info.host}/v2/tts?authorization=${info.authorization}&date=${info.date}&host=${info.host}`
      ),
    });
  },

  async onLoad(props) {
    uni.getSystemInfo({	//获取系统信息
		success: (res) => {
			this.swiperHeight = res.windowHeight + 40 + 'px'
		},
		fail: (res) => {
			console.log('error')
		}
	})//用于获取动态高度 改变swiper iTem

    this.dep = props.dep;
    this.depId = props.depId; 
    //二次重构新增 用于向后端获取问题列表v
    try{
      const response = await question.getIdList(props.depId)
      console.log("OK!:")
      console.log(response)
    }catch(err){
      console.warn("ERR!:"+err)
    }


    //
    for (const index in this.problems) {
      this.problems[index] = {
        index,
        ...this.problems[index],
      };
    }
    console.log(this.answers);
  },
  onShow() {
    uni.authorize({
      scope: "scope.record", //调取录音功能的权限申请
      fail: () => {
        this.$refs.popup.open();
      },
    });
  },
  data() {
    return {
      swiperHeight:"",
      problems: [
        // 问题列表
        {
          type: "answer",
          content: "请描述您从事的职业",
          //后端给的功能中没对于填空题的预选项功能
          defaultAnswers: [
            "教师",
            "医生",
            "学生",
            "工人",
            "金融行业",
            "快递行业",
            "计算机行业",
          ],
        },
        {
          type: "answer",
          content: "请描述您就医的主要原因",
          defaultAnswers: ["心脏疼痛", "胃疼", "头疼", "流鼻涕", "打喷嚏"],
        },
        {
          type: "answer",
          content: `请描述您的病程`,
          defaultAnswers: [
            "一天以内",
            "三天左右",
            "一个周以上",
            "一个月左右",
            "半年以上",
            "好几年了",
          ]
        },
        {
          type: "yes-no-answer",
          content: "有无呕吐症状",
          moreContent: "请描述您呕吐的频率和呕吐物的形状"
        },
        {
          type: "yes-no-answer",
          content: "平时有无不良饮食习惯",
          moreContent: "请描述您不良饮食习惯的详情",
          defaultAnswers: [
            "三餐不规律",
            "喜欢吃生冷辛辣的食物",
            "喜欢空腹和茶/咖啡"
          ]
        },{
          type:"choice",
          content:"选择题",
          defaultAnswers:[
            {
          choice_id: 0,
          content: "选项A",
        },
        {
          choice_id: 1,
          content: "选项B",
        },
        {
          choice_id: 2,
          content: "选项C",
        },{
          choice_id: 3,
          content:"选项D"
        }
          ]
        }
        
      ].concat({
        title: "提交",
      }),
      problemActive: 0,
      dep: "",
      depId:0,
      options: [
        {
          content: "1",
        },
        {
          content: "2",
        },
        {
          content: "3",
        },
        {
          content: "4",
        },
      ],
      answers: new Array(10).fill("", 0, 10),
      alphaBet: ["A", "B", "C", "D", "E", "F", "G"],
    };
  },
  methods: {
    swiperChange(e) {
      this.problemActive = e.detail.current;
    },
    swipeToNext() {
      if (this.problemActive >= this.problems.length - 1) {
        this.problemActive = this.problems.length - 1;
        return;
      }
      this.problemActive++;
    },
    swipeToPrevious() {
      this.problemActive--;
    },
    choose() {
      console.log(index)
      this.answers[this.problemActive] = value;
      uni.vibrateShort({
        success: () => {},
      });
      setTimeout(() => {
        this.swipeToNext();
      }, 200);
    },
    submit() {
      console.log(this.answers)
      uni.showToast({
        title: "成功，请稍等！",
      });
      uni.vibrateLong({
        success: () => {},
      });
      setTimeout(() => {
        console.log("nav");
        uni.navigateTo({
          url: "/pages/resultPage/resultPage",
          animationType: "fade-in",
          success: (res) => {
            console.log(res);
            res.eventChannel.emit("data", {
              problems: this.problems,
              answers: this.answers,
            });
          },
        });
      }, 500);
    },
    jumpToEnd() {
      this.problemActive = this.problems.length - 1;
    },
    openSetting() {
      uni.openSetting({
        fail(res) {
          // this.back() 实际使用的时候
          uni.showToast({
            title: "获取许可失败",
          });
        },
        success(res) {
          if (!res.authSetting["scope.record"])
            // uni.navigateBack({
            //   delta: -1,
            // });
            uni.showToast({
              title: "获取许可失败",
            });
        },
      });
    },
    back() {
      uni.navigateBack({
        delta: -1,
      });
    },
    input(index, e) {
      // console.log(e)
      this.answers[index] = e;
    },
    change(index,e) {
      console.log(e)
      // if (e === 0) {
      //   uni.showToast({
      //     title: "请进一步回答问题",
      //   });
      //   uni.vibrateLong({
      //     success: () => {},
      //   });
      //   setTimeout(() => {
      //     this.problems[index] = {
      //       ...this.problems[index],
      //       type: "answer",
      //       content: this.problems[index].moreContent,
      //     };
      //   }, 300);
      // } else {
        // uni.vibrateShort({
        //   success: () => {},
        // });
        this.answers[index] = e;
        setTimeout(() => {
          this.swipeToNext();
        }, 200);
      
    },
  },
  computed: {
    end() {
      return this.problemActive === this.problems.length - 1;
    },
    choiceArray() {
      return this.problems.filter(
        (item, index) =>
          index !== this.problems.length - 1 &&
          (item.type === "multi-choice" || item.type === "yes-no-answer")
      );
    },
    answerArray() {
      return this.problems.filter(
        (item, index) =>
          index !== this.problems.length - 1 && item.type === "answer"
      );
    },
    problemsContent(){
      return this.problems.slice(0,this.problems.length-1);
    }
  },
};
</script>

<style lang="scss" scoped>
.scrol{
  height: 100%;
}
.inner {
  display: flex;
  flex-direction: column;
  height: 100vh;

  .steps {
    margin: 10rpx 0rpx;
  }

  .swiper {
    flex-grow: 1;
    .swiper-item {
      display: flex;
      flex-direction: column;

      .problem-content {
        flex-grow: 1;
        display: flex;
        flex-direction: column;

        .answer {
          position: relative;
        }
      }
    }
  }
}

.out-grid {
  display: flex;
  flex-wrap: wrap;
  width: 100%;
  position: relative;

  .answer-grid {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    width: 150rpx;
    height: 150rpx;

    .single {
      border-radius: 50%;
      background-color: green;
      height: 60%;
      width: 60%;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }

  .answer-bar {
    width: 90%;
    border: 1px solid gray;
    position: relative;

    .answer-head {
      width: 100%;
    }
  }
}

.buttons {
  // border-radius: 0;
  // display: flex;

  // button {
  //   margin: 0;
  //   padding: 0;
  //   border-radius: 0;
  //   flex-grow: 1;
  // }

  // button:after {
  //   content: none;
  // }

  // button::after {
  //   border: none;
  // }
  margin: 25upx;
}
</style>
